import React, { Suspense } from 'react'
import { Spin } from 'antd'
import { matchRoutes, Navigate, useLocation } from 'react-router-dom'
import { useAuth } from '@/utils/auth'
import routes from './config'

import { message } from 'antd'

// auth router component
export const RouterAuth = ({ children }) => {
  let { isLogin, getUser } = useAuth()
  const location = useLocation()
  // match current level routing tree
  const match = matchRoutes(routes, location)

  // redirect if no element and redirect exists
  const { route: tmpRoute } = match.at(-1)
  if (tmpRoute.redirect) {
    return (
      <Navigate
        to={tmpRoute.redirect}
        state={{ from: location.pathname }}
        replace
      />
    )
  }
  // if needs auth
  const isNeedLogin = match?.some((item) => {
    const route = item.route
    // no match
    if (!route.meta) return false
    // return if needs auth
    return route.meta.auth != null
  })
  // auth level
  const authLevel = match?.reduce((max, cur) => {
    const { route } = cur
    const auth = route?.meta?.auth || 0
    return max > auth ? max : auth
  }, 0)

  // TODO if has auth
  const isAuth = () => {
    return authLevel > getUser().auth
  }

  // if needs auth and not login yet
  console.log(match)
  if (isNeedLogin && !isLogin) {
    message.error('Please login first')
    // jump to login page and store the former page
    return <Navigate to="/login" state={{ from: location.pathname }} replace />
  }

  // auth
  const isNeedAuth = isNeedLogin && authLevel && isAuth()
  if (isNeedAuth) {
    message.error('No Auth to visit')
    return <Navigate to="/" replace />
  }

  // return children as React.ReactElement
  return <>{children}</>
}

// show spin when loading
export function lazyLoad(Comp) {
  return (
    <Suspense
      fallback={
        <Spin
          size="large"
          style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center'
          }}
        />
      }
    >
      <Comp />
    </Suspense>
  )
}
